package com.subsequent.controller;

import com.subsequent.entity.Notice;
import com.subsequent.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/notices")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    // 分页+条件查询
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        int offset = (pageNum - 1) * pageSize;
        List<Notice> list = noticeService.selectByCondition(title, status, startTime, endTime);
        int total = noticeService.countByCondition(title, status, startTime, endTime);
        Map<String, Object> result = new HashMap<>();
        result.put("data", list.subList(Math.min(offset, list.size()), Math.min(offset + pageSize, list.size())));
        result.put("total", total);
        return result;
    }

    // 新增
    @PostMapping("/add")
    public String add(@RequestBody Notice notice) {
        noticeService.insert(notice);
        return "success";
    }

    // 编辑
    @PostMapping("/edit")
    public String edit(@RequestBody Notice notice) {
        noticeService.update(notice);
        return "success";
    }

    // 删除
    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        noticeService.deleteById(id);
        return "success";
    }

    // 详情
    @GetMapping("/detail/{id}")
    public Notice detail(@PathVariable("id") Integer id) {
        return noticeService.selectById(id);
    }
}